package cc.z8g.browser.core.search

import android.app.SearchManager
import android.content.Intent
import cc.z8g.browser.core.BrowserContract
import cc.z8g.browser.search.suggestions.SearchEngineProvider
import cc.z8g.browser.utils.QUERY_PLACE_HOLDER
import cc.z8g.browser.utils.smartUrlFilter

/**
 * Extracts data from an [Intent] and into a [BrowserContract.Action].
 */
object IntentExtractor {

    /**
     * Extract the action from the [intent] or return null if no data was extracted.
     */
    fun extractUrlFromIntent(intent: Intent): BrowserContract.Action? {
        return when (intent.action) {
            Intent.ACTION_WEB_SEARCH -> extractSearchFromIntent(intent)?.let(BrowserContract.Action::LoadUrl)
            else -> intent.dataString?.let(BrowserContract.Action::LoadUrl)
        }
    }

    private fun extractSearchFromIntent(intent: Intent): String? {
        val query = intent.getStringExtra(SearchManager.QUERY)
        val searchUrl = "${SearchEngineProvider.provideSearchEngine().queryUrl}$QUERY_PLACE_HOLDER"

        return if (query?.isNotBlank() == true) {
            smartUrlFilter(query, true, searchUrl)
        } else {
            null
        }
    }

}
